﻿using System.Globalization;
using System.Text.RegularExpressions;
using System.Windows;

namespace Oxage.CNC.Models
{
	public class ArcInline : XamlPathDataCodeInline
	{
		#region Constructors
		public ArcInline()
		{
		}

		public ArcInline(string inline)
		{
			Parse(inline);
		}
		#endregion

		#region Public properties
		public Size Size
		{
			get;
			set;
		}

		public double RotationAngle
		{
			get;
			set;
		}

		public bool IsLargeArcFlag
		{
			get;
			set;
		}

		public bool SweepDirectionFlag
		{
			get;
			set;
		}

		public Point EndPoint
		{
			get;
			set;
		}
		#endregion

		#region Public methods
		public override void Parse(string inline)
		{
			var match = Regex.Match(inline, @"(?<code>\w)\s*(?<rx>[\d\-\+\.]+)\s*,\s*(?<ry>[\d\-\+\.]+)\s+(?<angle>[\d\-\+\.]+)\s+(?<large>[\d]+)\s+(?<sweep>[\d]+)\s+(?<px>[\d\-\+\.]+)\s*,\s*(?<py>[\d\-\+\.]+)", RegexOptions.IgnoreCase);
			if (match.Success)
			{
				this.Code = match.Groups["code"].Value[0];

				double rx = double.Parse(match.Groups["rx"].Value, CultureInfo.InvariantCulture);
				double ry = double.Parse(match.Groups["ry"].Value, CultureInfo.InvariantCulture);
				double angle = double.Parse(match.Groups["angle"].Value, CultureInfo.InvariantCulture);
				int large = int.Parse(match.Groups["large"].Value, CultureInfo.InvariantCulture);
				int sweep = int.Parse(match.Groups["sweep"].Value, CultureInfo.InvariantCulture);
				double px = double.Parse(match.Groups["px"].Value, CultureInfo.InvariantCulture);
				double py = double.Parse(match.Groups["py"].Value, CultureInfo.InvariantCulture);

				this.Size = new Size(rx, ry);
				this.RotationAngle = angle;
				this.IsLargeArcFlag = (large == 1);
				this.SweepDirectionFlag = (sweep == 1);
				this.EndPoint = new Point(px, py);
			}
		}

		public override string ToString()
		{
			string xRadius = this.Size.Width.ToString(CultureInfo.InvariantCulture);
			string yRadius = this.Size.Height.ToString(CultureInfo.InvariantCulture);
			string angle = this.RotationAngle.ToString(CultureInfo.InvariantCulture);
			string large = (this.IsLargeArcFlag ? 1 : 0).ToString();
			string sweep = (this.SweepDirectionFlag ? 1 : 0).ToString();
			string xPoint = this.EndPoint.X.ToString(CultureInfo.InvariantCulture);
			string yPoint = this.EndPoint.Y.ToString(CultureInfo.InvariantCulture);
			return string.Format("A{0},{1} {2} {3} {4} {5},{6}", xRadius, yRadius, angle, large, sweep, xPoint, yPoint);
		}
		#endregion
	}
}
